// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, Image, TouchableOpacity, ImageBackground, ScrollView, InteractionManager } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/Ionicons';

// antd 按需加载
import { Tabs, Toast, Stepper, Portal, SwipeAction, Modal } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import * as ActionTypes from '../../constants/constants.js';
import { shopCartList, shopCartDel, shopCartUpdate, goodsDetail, goodsAttribute } from '../../module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, Radio, RefreshScrollView, Results, Attribute, Layout } from '../../components/index.js'

// 引入专用组件
import { } from './components'

// 引入工具包
import { background } from '../../util/images.js'
import { press, size, ScreenWidth, pathHead, defaultDataList, onEndReached, onRefresh, concatDataList, defaultPage } from '../../util/utils.js'

class ShoppingCart extends Component {


  constructor(props) {
    super(props)
    this.state = {
      refreshing: false,
      edit: false,
      goodDetail: {},
      goodsNumber: 1,
      attributeVisible: false,
      goodsId: '',
      productId: '',
      goodAttribute: [],
    }
  }

  componentDidMount() {
    this.loading = Toast.loading('加载中', 0)
    this.shopCartList(() => {
      Portal.remove(this.loading)
    })
  }

  shopCartList(callback) {
    shopCartList({
      current: 1,
      size: 9999
    }).then(res => {
      if (callback) {
        callback(res)
      }
    }).finally(() => {
      Portal.remove(this.loading)
    })
  }

  // shopCartUpdate(option) {
  //   const { goodsId, goodsNumber, id, productId } = option
  //   shopCartUpdate({
  //     goodsId,// integer($int64)商品ID
  //     goodsNumber,// integer($int32)商品数量
  //     id,// integer($int64)购物车ID
  //     productId,// integer($int64)产品ID
  //   }).then(res => {
  //     if (callback) {
  //       callback(res)
  //     }
  //   })
  // }

  shopCartDel(id) {
    const { shopCartCheckList } = this.props
    const { edit } = this.state
    let checkList = []
    for (let attr in shopCartCheckList) {
      if (shopCartCheckList[attr]) {
        checkList.push(attr)
      }
    }
    shopCartDel({
      ids: id ? [id] : checkList
    }).then(res => {
      this.shopCartList()
      this.setState({ edit: !edit })
      Toast.success('删除成功', 1)
    })
  }

  isDelete(id) {
    Modal.alert('删除', '确认删除选中商品', [
      {
        text: '取消',
        onPress: () => { },
        style: 'cancel',
      },
      { text: '确定', onPress: () => this.shopCartDel(id) },
    ]);
  }

  onRefresh = () => {
    const { edit } = this.state
    this.setState({ refreshing: true });
    this.shopCartList(() => {
      this.setState({ refreshing: false, edit: !edit });
    })
  }

  async openAttributeModal(option) {
    const { id, cartId, goodsId, productId, goodsNumber } = option
    this.loading = Toast.loading('加载中', 0)
    let detail = await goodsDetail({ goodsId: id })
    let attribute = await goodsAttribute({ goodsId: id, productId })
    this.setState({
      goodDetail: detail.data,
      goodAttribute: attribute.data,
      attributeVisible: true,
      id: cartId,
      goodsId: id,
      goodsNumber,
      productId
    }, () => {
      Portal.remove(this.loading)
    })
  }

  closeAttributeModal = () => {
    this.setState({
      attributeVisible: false
    })
  }

  handleSubmitOrder() {
    let { shopCartList, shopCartCheckList } = this.props
    shopCartList.records.map((item, index) => {
      shopCartList.records[index].checked = shopCartCheckList[item.cartId]
    })
    let goodsList = shopCartList.records.filter(item => {
      if (item.checked) {
        return item
      }
    }).map(item => {
      return {
        id: item.id,
        number: item.goodsNumber
      }
    })
    Actions.submitOrder({ goodsList })
  }

  getTotalPrice() {
    let { shopCartList, shopCartCheckList } = this.props
    let totarPrice = 0
    shopCartList.records.map((item, index) => {
      shopCartList.records[index].checked = shopCartCheckList[item.cartId]
    })
    shopCartList.records.filter(item => {
      if (item.checked) {
        return item
      }
    }).map(item => {
      totarPrice += item.goodsPrice * item.goodsNumber
    })
    return totarPrice
  }

  render() {
    const { refreshing, edit, goodDetail, goodsNumber, attributeVisible, goodsId, productId, goodAttribute, } = this.state
    const { shopCartList, shopCartCheckList, dispatch } = this.props
    console.log(shopCartCheckList)
    let checked = false
    let counter = 0
    let newShopCartCheckList = Object.values({ ...shopCartCheckList })
    newShopCartCheckList.map(item => {
      if (item) {
        counter++
      }
    })
    if (counter == shopCartList.records.length) {
      checked = true
    }
    return (
      <Layout
        style={{ backgroundColor: '#fff' }}
        header={<Status />}
        footer={
          <View style={{
            flexDirection: 'row',
            alignItems: 'center',
          }}>
            <View style={{
              height: 52,
              alignItems: 'center',
              flexDirection: 'row',
              flex: 1,
              paddingLeft: 15
            }}>
              <Radio
                style={{}}
                checked={checked}
                onChange={(value) => {
                  let newShopCartCheckList = { ...shopCartCheckList }
                  for (attr in newShopCartCheckList) {
                    newShopCartCheckList[attr] = value
                  }
                  dispatch({
                    type: ActionTypes.setShopCartCheckList,
                    data: newShopCartCheckList
                  })
                }}
                label={'全选'}
              />
              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginLeft: 15 }}>商品总价：￥{this.getTotalPrice()}</Text>
            </View>
            {edit ? (
              <TouchableOpacity
                style={{
                  height: 52,
                  width: ScreenWidth / 3,
                  backgroundColor: '#E5C67B'
                }}
                onPress={() => {
                  this.isDelete()
                }}>
                <Text style={{ fontSize: 14, color: '#fff', lineHeight: 52, textAlign: 'center' }}>删除</Text>
              </TouchableOpacity>
            ) : (
                <TouchableOpacity
                  style={{
                    height: 52,
                    width: ScreenWidth / 3,
                    backgroundColor: '#000000'
                  }}
                  onPress={() => {
                    this.handleSubmitOrder()
                  }}>
                  <Text style={{ fontSize: 14, color: '#fff', lineHeight: 52, textAlign: 'center' }}>去结算</Text>
                </TouchableOpacity>
              )}
          </View>
        }
      >
        <NavBar
          title="购物车"
          back={true}
          extra={edit ? '完成' : '编辑'}
          extraOnPress={() => {
            this.setState({
              edit: !edit
            })
          }}
        />
        <RefreshScrollView
          style={Style.content}
          refreshing={refreshing}
          onRefresh={this.onRefresh}
        >
          {shopCartList.records.map((item, index) => (
            <SwipeAction
              autoClose
              key={index}
              style={{
                height: 110,
                backgroundColor: '#fff'
              }}
              right={[
                {
                  text: '删除',
                  onPress: () => {
                    this.isDelete(item.cartId)
                  },
                  style: { backgroundColor: '#E5C67B', color: 'white' },
                },
              ]}
            >
              <View
                style={{
                  flexDirection: 'row',
                  padding: 15
                }}
              >
                <View style={{
                  alignItems: 'center',
                  justifyContent: 'center',
                  width: 22,
                }}>
                  <Radio
                    style={{}}
                    checked={shopCartCheckList[item.cartId]}
                    onChange={(value) => {
                      let newShopCartCheckList = { ...shopCartCheckList }
                      newShopCartCheckList[item.cartId] = value
                      dispatch({
                        type: ActionTypes.setShopCartCheckList,
                        data: newShopCartCheckList
                      })
                    }}
                    label={''}
                  />
                </View>
                <View style={{
                  width: 80,
                  marginLeft: 10
                }}>
                  <Image
                    resizeMod={"contain"}
                    style={{
                      width: 80,
                      height: 80,
                    }}
                    source={background}
                    source={{ uri: `${pathHead}${item.goodsMainPic}` }}
                  />
                </View>
                <View style={{
                  flexDirection: 'column',
                  justifyContent: 'space-between',
                  alignItems: 'flex-start',
                  height: 80,
                  marginLeft: 10,
                  flex: 1
                }}>
                  <Text
                    numberOfLines={1}
                    ellipsizeMode={'tail'}
                    style={{ fontSize: 15, color: '#000', lineHeight: 18, }}
                  >{item.goodsName}</Text>
                  <TouchableOpacity
                    style={{
                      padding: 3,
                      paddingHorizontal: 5,
                      backgroundColor: '#FAFAFA',
                      borderRadius: 2,
                      borderWidth: .5,
                      borderColor: '#EFEFEF'
                    }}
                    onPress={() => {
                      this.openAttributeModal(item)
                    }}
                  >
                    <View style={{ flexDirection: 'row', alignItems: 'center', }}>
                      <Text style={{ fontSize: 10, color: '#7F7F7F', lineHeight: 14, marginRight: 5 }}>{item.attrValue}</Text>
                      <Icon name="md-arrow-dropdown" size={10} color={'#7F7F7F'} />
                    </View>
                  </TouchableOpacity>
                  <View style={{
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                  }}>
                    <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', }}>
                      <Text style={{ fontSize: 14, color: '#E5C67B', lineHeight: 20, marginRight: 15 }}>¥{item.goodsPrice}</Text>
                      <Text style={{ fontSize: 14, color: '#E5C67B', lineHeight: 20, }}>CV:{item.cv}</Text>
                    </View>
                    <View style={{ width: 80 }}>
                      <Stepper
                        key="0"
                        min={0}
                        onChange={(value) => {
                          shopCartUpdate({
                            goodsId: item.id,
                            goodsNumber: value,
                            id: item.cartId,
                            productId: item.productId
                          }).then(res => {
                            this.shopCartList()
                          })
                        }}
                        inputStyle={{
                          fontSize: 12,
                          width: 30
                        }}
                        upStyle={{
                          width: 20,
                          height: 20
                        }}
                        downStyle={{
                          width: 20,
                          height: 20
                        }}
                        styles={{
                          stepWrap: {
                            width: 20,
                            height: 20
                          },
                          stepText: {
                            fontSize: 12,
                            lineHeight: 16
                          }
                        }}
                        value={item.goodsNumber}
                      />
                    </View>
                  </View>
                </View>
              </View>
            </SwipeAction>
          ))}
          {shopCartList.length <= 0 && <Results type='data' width={size(500)} height={size(200)} title="购物车是空的" />}
        </RefreshScrollView>

        {
          attributeVisible && (
            <Attribute
              goodDetail={goodDetail}
              goodsNumber={goodsNumber}
              visible={attributeVisible}
              onClose={this.closeAttributeModal}
              goodsId={goodsId}
              productId={productId}
              goodAttribute={goodAttribute}
              onPress={(option) => {
                // Actions.refresh({ goodsId: option.goodsId, productId: option.productId, refresh: true })
              }}
              defaultBtn={"关闭"}
              defaultBtnOnPress={(option) => {
                this.closeAttributeModal()
              }}
              confirmBtn={"确定"}
              confirmBtnOnPress={(option) => {
                shopCartUpdate({
                  goodsId: option.goodsId,
                  goodsNumber: option.goodsNumber,
                  productId: option.productId,
                  id: this.state.id,
                }).then(res => {
                  this.closeAttributeModal()
                  this.onRefresh()
                })
              }}
            />
          )
        }
      </Layout>
    );
  }
}

export default connect(({ user, shopCartList, shopCartCheckList }) => ({
  user, shopCartList, shopCartCheckList
}))(pureRender(ShoppingCart))

